package org.dromara.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.dromara.admin.domain.*;
import org.dromara.admin.domain.bo.OrderProductBo;
import org.dromara.admin.domain.bo.OrderProductPriceBo;
import org.dromara.admin.domain.vo.*;
import org.dromara.admin.enums.CustomerTypeEnum;
import org.dromara.admin.enums.GeneralEnum;
import org.dromara.admin.enums.IsCancelEnum;
import org.dromara.admin.enums.SettlementStatusEnum;
import org.dromara.admin.service.*;
import org.dromara.admin.utils.SpliceAddressUtils;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.dromara.admin.domain.bo.OrderBo;
import org.dromara.admin.mapper.OrderMapper;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 订单主（客户ID和供应商ID必须二选一，由应用程序保证）Service业务层处理
 *
 * @author Lion Li
 * @date 2025-10-10
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class OrderServiceImpl implements IOrderService {

    private final OrderMapper baseMapper;
    private final IEmployeeService employeeService;
    private final ICustomerService customerService;
    private final ISupplierService supplierService;
    private final ITemplateMarketService templateMarketService;
    private final IOrderProductService orderProductService;

    /**
     * 查询订单
     *
     * @param id 主键
     * @return 订单主（客户ID和供应商ID必须二选一，由应用程序保证）
     */
    @Override
    public OrderVo queryById(Long id) {
        // 使用MPJBaseMapper进行联表查询order、order_product
        MPJLambdaWrapper<Order> wrapper = new MPJLambdaWrapper<Order>()
            .selectAll(Order.class)//查询Employee表全部字段
            .selectCollection(OrderProduct.class, OrderVo::getOrderProductList)
            .leftJoin(OrderProduct.class, OrderProduct::getOrderId, Order::getId)
            .eq(Order::getId, id);
        OrderVo orderVo = baseMapper.selectJoinOne(OrderVo.class, wrapper);
        if (BeanUtil.isEmpty(orderVo)) {
            throw new ServiceException("订单信息不存在！");
        }
        return orderVo;
    }

    /**
     * 分页查询订单主列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 订单主（客户ID和供应商ID必须二选一，由应用程序保证）分页列表
     */
    @Override
    public TableDataInfo<OrderVo> queryPageList(OrderBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Order> lqw = buildQueryWrapper(bo);
        Page<OrderVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 获取符合条件的订单总金额
     *
     * @param bo
     * @return
     */
    @Override
    public BigDecimal getTotalActualAmount(OrderBo bo) {
        // 获取当前登录用户的公司ID
        EmployeeVo employeeVo = employeeService.queryById(bo.getCompanyId());
        bo.setCompanyId(employeeVo.getCompanyId());
        LambdaQueryWrapper<Order> lqw = buildQueryWrapper(bo);

        // 查询符合条件的所有订单 actualAmount，并累加
        return baseMapper.selectList(lqw).stream()
            .map(Order::getActualAmount)
            .filter(Objects::nonNull)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    /**
     * 分页查询当前用户主体的订单列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return
     */
    @Override
    public TableDataInfo<OrderVo> queryPageMyOrderList(OrderBo bo, PageQuery pageQuery) {
        // 获取当前登录用户的公司ID
        EmployeeVo employeeVo = employeeService.queryById(bo.getCompanyId());
        bo.setCompanyId(employeeVo.getCompanyId());
        LambdaQueryWrapper<Order> lqw = buildQueryWrapper(bo);
        Page<OrderVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        // 查询符合条件的所有订单 actualAmount，并累加
        BigDecimal totalActualAmount = baseMapper.selectList(lqw).stream()
            .map(Order::getActualAmount)
            .filter(Objects::nonNull)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
        return TableDataInfo.build(result, totalActualAmount);
    }

    /**
     * 查询符合条件的订单列表
     *
     * @param bo 查询条件
     * @return 订单主列表
     */
    @Override
    public List<OrderVo> queryList(OrderBo bo) {
        LambdaQueryWrapper<Order> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Order> buildQueryWrapper(OrderBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Order> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(Order::getCreateTime);
        lqw.like(StringUtils.isNotBlank(bo.getOrderNo()), Order::getOrderNo, bo.getOrderNo());
        lqw.like(StringUtils.isNotBlank(bo.getCreatorName()), Order::getCreatorName, bo.getCreatorName());
        lqw.eq(bo.getOrderType() != null, Order::getOrderType, bo.getOrderType());
        lqw.eq(bo.getSettleStatus() != null, Order::getSettleStatus, bo.getSettleStatus());
        lqw.eq(bo.getTagId() != null, Order::getTagId, bo.getTagId());
        lqw.eq(bo.getAddressId() != null, Order::getAddressId, bo.getAddressId());
        lqw.like(StringUtils.isNotBlank(bo.getCustomerName()), Order::getCustomerName, bo.getCustomerName());
        lqw.like(StringUtils.isNotBlank(bo.getCustomerContactName()), Order::getCustomerContactName, bo.getCustomerContactName());
        lqw.like(StringUtils.isNotBlank(bo.getCustomerPhone()), Order::getCustomerPhone, bo.getCustomerPhone());
        lqw.like(StringUtils.isNotBlank(bo.getCustomerAddress()), Order::getCustomerAddress, bo.getCustomerAddress());
        lqw.eq(bo.getCustomerType() != null, Order::getCustomerType, bo.getCustomerType());
        lqw.eq(bo.getCompanyId() != null, Order::getCompanyId, bo.getCompanyId());
        lqw.like(StringUtils.isNotBlank(bo.getCompanyName()), Order::getCompanyName, bo.getCompanyName());
        lqw.like(StringUtils.isNotBlank(bo.getCompanyContactName()), Order::getCompanyContactName, bo.getCompanyContactName());
        lqw.like(StringUtils.isNotBlank(bo.getCompanyAddress()), Order::getCompanyAddress, bo.getCompanyAddress());
        lqw.like(StringUtils.isNotBlank(bo.getCompanyPhone()), Order::getCompanyPhone, bo.getCompanyPhone());
        lqw.like(StringUtils.isNotBlank(bo.getExpressNo()), Order::getExpressNo, bo.getExpressNo());
        lqw.like(StringUtils.isNotBlank(bo.getExpressCompany()), Order::getExpressCompany, bo.getExpressCompany());
        lqw.eq(bo.getIsCancel() != null, Order::getIsCancel, bo.getIsCancel());
        lqw.ge(bo.getStartTime() != null, Order::getCreateTime, bo.getStartTime());
        lqw.le(bo.getEndTime() != null, Order::getCreateTime, bo.getEndTime());
        return lqw;
    }

    /**
     * 新增订单
     *
     * @param bo 订单主（客户ID和供应商ID必须二选一，由应用程序保证）
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(OrderBo bo) {
        Order add = MapstructUtils.convert(bo, Order.class);
        // 获取当前登录用户信息包含主体公司信息
        EmployeeVo employeeVo = employeeService.queryById(add.getCreatorId());
        Long companyId = employeeVo.getCompanyId(); // 主体公司ID

        // === 生成订单编号 ===，主体四位唯一编码-年份-自增ID(根据公司自增，5位数字)
        String orderNo = getOrderNo(add.getCreatorId());
        add.setOrderNo(orderNo);
        add.setCreatorName(employeeVo.getRealName());

        // 设置收单方信息，根据customer_type字段判断是客户还是供应商进行信息设置
        if (CustomerTypeEnum.CUSTOMER.equals(add.getCustomerType())) {
            CustomerVo customerVo = customerService.queryById(add.getCustomerId());
            add.setCustomerName(customerVo.getCustomerName()); // 收方名称
            add.setCustomerContactName(customerVo.getContactPerson()); // 收方联系人
            add.setCustomerPhone(customerVo.getPhone()); // 收方联系电话
            add.setCustomerAddress(SpliceAddressUtils.spliceAddress(customerVo)); // 收方地址
        } else if (CustomerTypeEnum.SUPPLIER.equals(add.getCustomerType())) {
            SupplierVo supplierVo = supplierService.queryById(add.getCustomerId());
            add.setCustomerName(supplierVo.getSupplierName()); // 收方名称
            add.setCustomerContactName(supplierVo.getContactPerson()); // 收方联系人
            add.setCustomerPhone(supplierVo.getPhone()); // 收方联系电话
            add.setCustomerAddress(SpliceAddressUtils.spliceAddress(supplierVo)); // 收方地址
        }

        // 设置开单方主体信息
        add.setCompanyId(companyId); // 主体ID
        add.setCompanyName(employeeVo.getCompany().getName()); // 主体名称
        add.setCompanyContactName(employeeVo.getCompany().getContactPerson1()); // 联系人
        add.setCompanyAddress(SpliceAddressUtils.spliceAddress(employeeVo.getCompany())); // 主体地址
        add.setCompanyPhone(employeeVo.getCompany().getContact1()); // 电话

        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (!flag) {
            throw new ServiceException("新增订单失败");
        }
        bo.setId(add.getId()); // 返回主键
        bo.setCompanyId(companyId); // 返回主体ID

        // === 保存订单产品明细 + 更新价格记录 ===
        orderProductService.saveOrderPAnd2PByOrderBo(bo);

        // 使用模版后增加模版次数
        templateMarketService.addTemplateUsedCount(add.getTemplateId());
        return Boolean.TRUE;
    }

    /**
     * 获取最新订单编号
     *
     * @param userId 用户ID
     * @return 订单编号
     */
    @Override
    public String getOrderNo(Long userId) {
        // 获取当前登录用户信息包含主体公司信息
        EmployeeVo employeeVo = employeeService.queryById(userId);
        Long companyId = employeeVo.getCompanyId(); // 主体公司ID

        // === 生成订单编号 ===，主体四位唯一编码-年份-自增ID(根据公司自增，5位数字)
        String companyPrefix = employeeVo.getCompany().getCompanyCode();
        int year = DateUtil.thisYear();
        // ==== 并发安全：按公司 + 年份生成序列 ====
        synchronized (("ORDER_NO_" + companyId + "_" + year).intern()) {
            // 统计当前公司当年已有订单数量
            Long count = baseMapper.selectCount(new LambdaQueryWrapper<Order>()
                .eq(Order::getCompanyId, companyId)
                .apply("YEAR(create_time) = {0}", year) // 根据 create_time 的年份过滤（MySQL 语法）
            );
            long nextNumber = count + 1;
            String seq = String.format("%05d", nextNumber);
            return companyPrefix + "-" + year + "-" + seq;
        }
    }

    /**
     * 修改订单
     *
     * @param bo 订单主（客户ID和供应商ID必须二选一，由应用程序保证）
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(OrderBo bo) {
        Order update = MapstructUtils.convert(bo, Order.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 添加订单物流信息
     *
     * @param bo 订单物流信息
     * @return 是否添加成功
     */
    @Override
    public Boolean addExpressInfo(OrderBo bo) {
        EmployeeVo employeeVo = employeeService.queryById(bo.getCreatorId());
        // 根据ID查询数据库信息
        Order order = baseMapper.selectById(bo.getId());
        if (BeanUtil.isEmpty(order)) {
            throw new ServiceException("订单信息不存在！");
        }
        if (!employeeVo.getCompanyId().equals(order.getCompanyId())) {
            throw new ServiceException("您没有权限操作此订单！");
        }
        if (IsCancelEnum.N.equals(order.getIsCancel())) {
            throw new ServiceException("订单已作废，无法补充物流信息！");
        }
        if (StrUtil.isNotEmpty(order.getExpressNo()) || StrUtil.isNotEmpty(order.getExpressCompany())) {
            throw new ServiceException("订单已添加物流信息，请勿重复添加！");
        }
        order.setExpressNo(bo.getExpressNo());
        order.setExpressCompany(bo.getExpressCompany());
        boolean result = baseMapper.updateById(order) > 0;
        if (!result) {
            throw new ServiceException("添加订单物流信息失败！");
        }
        return Boolean.TRUE;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Order entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除订单信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 首页面板获取订单统计信息
     *
     * @param companyId 公司ID
     * @param start     开始时间
     * @param end       结束时间
     */
    @Override
    public Map<String, Object> getOrderStats(Long companyId, DateTime start, DateTime end) {
        Map<String, Object> stats = new HashMap<>();

        // 订单数量
        long orderCount = baseMapper.selectCount(
            new LambdaQueryWrapper<Order>()
                .eq(Order::getCompanyId, companyId)
                .between(Order::getCreateTime, start, end)
                .eq(Order::getIsCancel, GeneralEnum.Y)
        );

        // 销售额合计
        Object sumObj = baseMapper.selectObjs(
            new QueryWrapper<Order>()
                .eq("is_cancel", GeneralEnum.Y)
                .eq("company_id", companyId)
                .between("create_time", start, end)
                .select("IFNULL(SUM(actual_amount),0)")
        ).stream().findFirst().orElse(0);

        BigDecimal salesAmount = NumberUtil.toBigDecimal(sumObj.toString());

        stats.put("orderCount", orderCount);
        stats.put("salesAmount", salesAmount);
        return stats;
    }

    /**
     * 根据主体公司ID获取最近10条订单列表
     *
     * @param companyId 公司ID
     */
    @Override
    public List<Order> queryRecent10OrderListByCompanyId(Long companyId) {
        return baseMapper.selectList(
            new LambdaQueryWrapper<Order>()
                .eq(Order::getCompanyId, companyId)
                .orderByDesc(Order::getCreateTime)
                .last("LIMIT 10"));
    }

    /**
     * 作废订单
     *
     * @param orderId 订单ID
     * @return 是否作废成功
     */
    @Override
    public Boolean cancel(Long orderId) {
        Order order = baseMapper.selectById(orderId);
        if (BeanUtil.isEmpty(order)) {
            throw new ServiceException("订单不存在");
        }
        if (IsCancelEnum.N.equals(order.getIsCancel())) {
            throw new ServiceException("订单已作废");
        }
        order.setIsCancel(IsCancelEnum.N);
        return baseMapper.updateById(order) > 0;
    }
}
